package com.eclab.web.controller;

import com.eclab.dto.User;
import com.eclab.security.core.properties.SecurityProperties;
import com.fasterxml.jackson.annotation.JsonView;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author yd
 * @Date 2018/10/8 09:58
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private ProviderSignInUtils providerSignInUtils;

    @Autowired
    private SecurityProperties securityProperties;

    Logger logger = LoggerFactory.getLogger(getClass());

    @PostMapping("/regist")
    public void regist(User user, HttpServletRequest request){
        //注册用户
        logger.info("注册用户，{}",user.getUsername());
        //不管是注册用户还是绑定用户，都会拿到一个用户唯一标识
        String userId = user.getUsername();
        providerSignInUtils.doPostSignUp(userId, new ServletWebRequest(request));
    }

    @GetMapping
    @JsonView(User.UserSimpleView.class)
    public List<User> query(@RequestParam(required = false) String username) {
        List<User> users = new ArrayList<>();
        users.add(new User());
        users.add(new User());
        users.add(new User());
        return users;
    }

    @GetMapping("/{id:\\d++}")
    @JsonView(User.UserDetailView.class)
    public User getInfo(@PathVariable String id){
        User user = new User();
        user.setId(id);
        user.setUsername("tom");
        user.setPassword("123456");
        return user;
    }

    @PostMapping
    public User create(@RequestBody User user){
        System.out.println(user.getUsername());
        user.setId("1");
        return user;
    }

    @PutMapping("/{id:\\d++}")
    public User update(@Valid @RequestBody User user, BindingResult bindingResult){
        System.out.println(user.getUsername());
        user.setId("1");
        if (bindingResult.hasErrors()){
            bindingResult.getAllErrors().stream().forEach(e->{
                System.out.println(e.getDefaultMessage());
            });
        }
        return user;
    }

    @DeleteMapping("/{id:\\d++}")
    public void delete(@PathVariable String id){
        System.out.println(id);
    }

    @GetMapping("/me")
    public Object getCurrentUser(Authentication  user,HttpServletRequest request) {

        String header = request.getHeader("Authorization");
        String token = StringUtils.substringAfter(header, "bearer");

        Claims claims = Jwts.parser().setSigningKey(securityProperties.getoAuth2().getJwtSigninKey())
                    .parseClaimsJws(token).getBody();

        String company = (String) claims.get("company");

        logger.info("company:{}", company);

        return user;
    }
}
